<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
      
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户名称">
         
          <cus-select disabled v-decorator="['cusId', { rules: [{ required: true, message: '请选择客户!' }] }]"/>
        </a-form-item>
        <!-- <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系人ID">
          <a-select show-search  placeholder="请选择"
              option-filter-prop="children" style="width: 100%"
              :filter-option="filterOption" @change="handleChange"
              disabled v-decorator="['relaId', { rules: [{ required: true, message: '请选择!' }] }]"
            >
            <a-select-option v-for="t in relaIdOptions" :key="t.value">{{t.text}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item  :labelCol="labelCol" :wrapperCol="wrapperCol" label="关联商机">
          <a-select show-search  placeholder="请选择"
              option-filter-prop="children" style="width: 100%"
              :filter-option="filterOption" @change="handleChange"
              disabled v-decorator="['busId', { rules: [{ required: false, message: '请选择!' }] }]"
            >
            <a-select-option v-for="t in busIdOptions" :key="t.value">{{t.text}}</a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="跟进人">
          <j-dict-select-tag disabled v-decorator="['ownerUserId', {}]" placeholder="请选择用户" :triggerChange="true"
           dictCode="sys_user,realname,id,sales=1 order by create_time"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="往来方式">
          <j-dict-select-tag disabled v-decorator="['way', {rules: [{ required: true, message: '请选择!' }]}]" 
          title="客户类型" :triggerChange=true dictCode="exchangeWay"
            placeholder="请选择" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="联系方式(地址)">
          <a-input placeholder="请输入联系方式(地址)" disabled v-decorator="['phone', {}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="计划时间">
          <a-date-picker showTime format='YYYY-MM-DD HH:mm:ss' disabled v-decorator="[ 'planDate', 
          {rules: [{ required: false, message: '请选择!' }]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="状态">
          <j-dict-select-tag disabled v-decorator="['way', {rules: [{ required: true, message: '请选择!' }]}]" 
          title="客户类型" :triggerChange=true dictCode="exchangeStatus"
            placeholder="请选择" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="往来内容">
          <a-textarea placeholder="请输入往来内容" disabled v-decorator="['content', {rules: [{ required: true, message: '请选择!' }]}]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="备注">
          <a-textarea placeholder="请输入备注" disabled v-decorator="['remark', {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="创建人">
          <j-dict-select-tag disabled v-decorator="['createId', {}]" placeholder="请选择用户" :triggerChange="true"
           dictCode="sys_user,realname,id"/>
        </a-form-item>
       <!-- <a-cascader
                    :allowClear="false"
                    :options="projectAreaOptions"
                    v-model="projectArea"
                    placeholder="请选择区域"
                    :loadData="loadAreaData"
                    @change="onAreaChange"
                    :getPopupContainer="(trigger) => {return trigger.parentElement}">
                </a-cascader> -->
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction,getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
  import { filterObj } from '@/utils/util';
  import  CusSelect  from '@/views/crm/comp/CusSelect';

  export default {
    name: "lookForm",
    components:{
      CusSelect
    },
    data () {
      return {
        projectAreaOptions:[],
        projectArea:[],
        cusIdOptions:[],
        busIdOptions:[],
        relaIdOptions:[],
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
        createUserId:{rules: [{ required: true, message: '请输入创建人ID!' }]},
        },
        url: {
          add: "/crm/exchange/add",
          edit: "/crm/exchange/edit",
          getcusId: "/crm/cus/getcusId",
          getbusId: "/crm/bus/getbusId",
          getrelaId: "/crm/rela/getrelaId",
        },
      }
    },
    created () {
        this.getcusIdOptions();
    },
    async mounted() {
        this.projectAreaOptions=await this.getAreaList() || [];
        console.log( this.projectAreaOptions);
     },
    methods: {
      look (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'cusId','relaId','busId','way','phone','status','ownerUserId','content','remark','createId'))
		  //时间格式化
          this.form.setFieldsValue({planDate:this.model.planDate?moment(this.model.planDate):null})
        });

      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            formData.planDate = formData.planDate?formData.planDate.format('YYYY-MM-DD HH:mm:ss'):null;
            
            console.log(formData)
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })



          }
        })
      },
      handleCancel () {
        this.close()
      },
     
      getcusIdOptions(){
        httpAction(this.url.getcusId, '', 'get')
          .then((res) => {
            if (res.success) {
             this.cusIdOptions=res.result;
            } else {
              that.$message.warning(res.message)
            }
          })
          
      },
      getrelaIdOptions(cusId){
        var param={"cusId":cusId};
        getAction(this.url.getrelaId, filterObj(param))
          .then((res) => {
            if (res.success) {
             this.relaIdOptions=res.result;
            } else {
              that.$message.warning(res.message)
            }
          })
          
      },
      getbusIdOptions(cusId){
        var param={"cusId":cusId};
        getAction(this.url.getbusId, filterObj(param))
          .then((res) => {
            if (res.success) {
             this.busIdOptions=res.result;
            } else {
              that.$message.warning(res.message)
            }
          })
          
      },
      handleChangeCus(value) {
            console.log(`selected ${value}`);
            this.getrelaIdOptions(value);
            this.getbusIdOptions(value);
      },
      handleChange(value) {
            console.log(`selected ${value}`);
      },
      filterOption(input, option) {
        return (
         option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      getAreaList(code) {
        var param={"code":code};
        return getAction("/region/getRegion",filterObj(param)).then(res => {
          let arr = res.map(item => {
                  return {
                      value: item.id,
                      label: item.label,
                      isLeaf: item.isLeaf,
                  }
              })
          return arr;
        })
      
      },
      //获取下一级数据
      async loadAreaData(selectedOptions) {           
          if (!this.projectAreaOptions.length) {
              this.projectAreaOptions = await this.getAreaList() || [];
          } else {
              const targetOption = selectedOptions[selectedOptions.length - 1];
              console.log(targetOption);
              targetOption.loading = true;
              const data = await this.getAreaList(targetOption.value);
              console.log(data, 'targetOption.value', targetOption.value);
              if (data.length) {
                  for (let index = 0; index < data.length; index ++) {
                      const element = data[index];
                      if (element.children) { delete  element.children }
                      element.value = element.value;
                      element.isLeaf = element.isLeaf;;
                  }
                  targetOption.loading = false;
                  targetOption.children = [...data];                   
                  this.projectAreaOptions = JSON.parse( JSON.stringify(this.projectAreaOptions) );
              } else {
                  targetOption.loading = false;
                  targetOption.isLeaf = true;
              }
          }
      },
      //选择区域后的操作
      onAreaChange(val, selectedOptions) {
          console.log(val, selectedOptions, 'val, selectedOptions')
      },
    }
  }
</script>

<style lang="less" scoped>

</style>